#include "eventloop.h"
#include "fcntl.h"

EventLoop::EventLoop()
{
}

EventLoop::~EventLoop()
{
}

void EventLoop::runLoop()
{
    while(1)
    {
        //获取已经准备好的描述符事件
        handleEvents(waitEvent());
    }
}
void EventLoop::handleEvents(int size)
{
    int fd = 0;
    for(int i = 0; i < size; i++)
    {
        fd = m_events[i].data.fd;
        //根据描述符的类型和事件类型进行处理
        if((isListenFD(fd)) && (m_events[i].events & EPOLLIN))
        {
            m_handerMap[fd]->handleAccept();
        }else if(m_events[i].events & EPOLLIN)
        {
            m_handerMap[fd]->handleRead();
        }else if(m_events[i].events & EPOLLOUT)
        {
            m_handerMap[fd]->handleWrite();
        }
    }
}

bool EventLoop::isListenFD(int fd)
{
    for(int i = 0; i < m_listenList.size(); i++)
    {
        if(fd == m_listenList.at(i)) return true;
    }

    return false;
}

int EventLoop::setNonBlocking(int fd)
{
    int oldOption = fcntl(fd, F_GETFL);
    int newOption = oldOption | O_NONBLOCK;
    fcntl(fd, F_SETFL, newOption);
    return oldOption;
}

bool EventLoop::registerServerEvent(int fd, HandlePtr handler)
{
    m_listenList.push_back(fd);
    m_handerMap[fd] = handler;
    if(addEvent(fd, EPOLLIN))
    {
        setNonBlocking(fd);
        return true;
    }

    printf("Error: %d register Event!\n", fd);
    return false;
}

bool EventLoop::registerSocketEvent(int fd, HandlePtr handler)
{
    m_handerMap[fd] = handler;
    if(addEvent(fd, EPOLLIN))
    {
        setNonBlocking(fd);
        return true;
    }

    printf("Error: %d register Event!\n", fd);
    return false;
}
